package com.example.myblog.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yx
 */
@Component
public class ElasticUtil {
    ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    public void setElasticsearchRestTemplate(ElasticsearchRestTemplate elasticsearchRestTemplate) {
        this.elasticsearchRestTemplate = elasticsearchRestTemplate;
    }

    public <T> List<T> searchAll(NativeSearchQuery searchQuery,Class c) {
        SearchHits<T> hits = elasticsearchRestTemplate.search(searchQuery, c);
        List<T> list = hits.getSearchHits().stream().map(hit->{
            T t = hit.getContent();
            return t;
        }).collect(Collectors.toList());
        return list;
    }
}
